package cn.simple.filetools.poi.excel.support;

import cn.simple.filetools.annotation.Excel;
import cn.simple.filetools.annotation.Excels;
import cn.simple.filetools.enums.OperateType;
import cn.simple.filetools.exception.NoAnnotationException;
import cn.simple.filetools.exception.PermissionErrorException;
import cn.simple.filetools.exception.ReadExcelException;
import cn.simple.filetools.poi.excel.PoiExcelDataConvertProcessor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author jiangjinjian
 * @date 2024/8/27 20:17
 * @description 默认poi-excel数据转换处理器
 */
@Component
@Slf4j
public class DefaultPoiExcelDataConvertProcessor implements PoiExcelDataConvertProcessor {
    @Override
    public <T> T convertAsClass(Row currRow, Class<T> tClass) {
        Map<Integer, String> data = convertAsMap(currRow);
        Object o;
        try {
            Excels excels = tClass.getAnnotation(Excels.class);
            if (excels == null) {
                throw new NoAnnotationException(String.format("类型[%s]缺少[Excels]注解", tClass.getTypeName()));
            }
            //只有存在导入操作类型的对象才可以进行读取
            if (!OperateType.IMPORT_OPERATE_LIST.contains(excels.operateType())) {
                throw new PermissionErrorException(String.format("类型[%s]缺少[导入]权限", tClass.getTypeName()));
            }
            //获取表头
            Map<Integer, List<String>> headTitleMap = new HashMap<>();
            for (int i = 0; i < excels.headRows(); i++) {
                Map<Integer, String> headMap = convertAsMap(currRow.getSheet().getRow(i));
                headMap.forEach((columnIndex, desc) -> {
                    if (!headTitleMap.containsKey(columnIndex)) {
                        headTitleMap.put(columnIndex, new ArrayList<>());
                    }
                    headTitleMap.get(columnIndex).add(desc);
                });
            }
            //map结构{列下表，每一个表头下标}
            o = tClass.newInstance();
            int i = 0;
            for (Field field : tClass.getDeclaredFields()) {
                field.setAccessible(true);
                Excel annotation = field.getAnnotation(Excel.class);
                //如果Excel注解不存在，默认按照属性顺序赋值列的顺序
                if (annotation == null) {
                    field.set(o, data.get(i));
                } else {
                    int index = headTitleMap.entrySet().stream().filter(e -> e.getValue().contains(annotation.value()) && annotation.value() != null)
                            .map(Map.Entry::getKey).findAny().orElse(annotation.cellIndex());
                    field.set(o, data.get(index));
                }
                i++;
            }
        } catch (InstantiationException | IllegalAccessException | RuntimeException e) {
            log.error(e.getMessage(), e);
            throw new ReadExcelException(e);
        }
        return (T) o;
    }

    @Override
    public Map<Integer, String> convertAsMap(Row currRow) {
        int cellNum = currRow.getLastCellNum();
        //获取合并行列数据
        List<CellRangeAddress> combineCellRangeList = getCombineCell(currRow.getSheet());
        Map<Integer, String> rowMap = new HashMap<>();
        for (int i = 0; i < cellNum; i++) {
            rowMap.put(i, getCurrCellStringValue(combineCellRangeList, currRow.getCell(i), currRow.getSheet()));
        }
        return rowMap;
    }

    /**
     * 3、判断单元格是否为合并单元格
     *
     * @param listCombineCell 存放合并单元格的list
     * @param cell            需要判断的单元格
     * @param sheet           sheet
     */
    protected String getCurrCellStringValue(List<CellRangeAddress> listCombineCell, Cell cell, Sheet sheet) {
        if (listCombineCell == null || listCombineCell.isEmpty()) {
            return convertCellValueToString(cell);
        }
        //3.1、设置第一个单元格和最后一个单元格的值
        int firstColumn = 0;
        int lastColumn = 0;
        //3.2、设置第一个单元格和最后一个行的值
        int firstRow = 0;
        int lastRow = 0;
        //3.3、初始化单元格值
        String cellValue = null;
        for (CellRangeAddress rangeAddress : listCombineCell) {
            //3.3.1、获得合并单元格的起始行, 结束行, 起始列, 结束列
            firstColumn = rangeAddress.getFirstColumn();
            lastColumn = rangeAddress.getLastColumn();
            firstRow = rangeAddress.getFirstRow();
            lastRow = rangeAddress.getLastRow();
            //3.3.2、判断是不是合并单元格
            if (cell.getRowIndex() >= firstRow && cell.getRowIndex() <= lastRow) {
                if (cell.getColumnIndex() >= firstColumn && cell.getColumnIndex() <= lastColumn) {
                    //3.3.2.1、获取行数据
                    Row fRow = sheet.getRow(firstRow);
                    //3.3.2.2、获取单元格数据
                    Cell fCell = fRow.getCell(firstColumn);
                    //3.3.2.3、对有合并单元格的数据进行格式处理
                    cellValue = convertCellValueToString(fCell);
                    break;
                }
            } else {
                //3.3.3、对没有合并单元格的数据进行格式处理
                cellValue = convertCellValueToString(cell);
            }
        }
        //3.4、返回处理后的单元格数据
        return cellValue;
    }

    /**
     * 2、处理合并单元格里面的数据
     *
     * @param sheet 工作薄
     * @return 返回合并单元格后里面的数据
     */
    protected List<CellRangeAddress> getCombineCell(Sheet sheet) {
        List<CellRangeAddress> list = new ArrayList<>();
        //2.1、获得一个 sheet 中合并单元格的数量
        int sheetMergerCount = sheet.getNumMergedRegions();
        //2.2、遍历合并单元格
        for (int i = 0; i < sheetMergerCount; i++) {
            //2.2.1、获得合并单元格加入list中
            CellRangeAddress rangeAddress = sheet.getMergedRegion(i);
            list.add(rangeAddress);
        }
        return list;
    }

    /**
     * 1、将单元格的内容转换为字符串
     *
     * @param cell 单元格
     * @return 返回转换后的字符串
     */
    private String convertCellValueToString(Cell cell) {
        //1.1、判断单元格的数据是否为空
        if (cell == null) {
            return null;
        }
        //1.2、设置单元格数据的初始值
        String cellValue = null;
        //1.3、获取单元格数据的类型
        switch (cell.getCellType()) {
            case NUMERIC:
                //1.3.1、获取到单元格数据的格式
                short dataFormat = cell.getCellStyle().getDataFormat();
                if (DateUtil.isCellDateFormatted(cell)) {
                    SimpleDateFormat sdf = null;
                    //1.3.1.1、处理日期格式，根据不同日期长度去判断
                    switch (dataFormat) {
                        case 14:
                            sdf = new SimpleDateFormat("yyyy/MM/dd");
                            break;
                        case 21:
                            sdf = new SimpleDateFormat("HH:mm:ss");
                            break;
                        case 22:
                            sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                            break;
                    }
                    //1.3.1.2、处理时间格式
                    Date date = cell.getDateCellValue();
                    assert sdf != null;
                    cellValue = sdf.format(date);
                } else if (dataFormat == 0) {
                    //1.3.2、处理普通数字格式
                    DecimalFormat format = new DecimalFormat("0");
                    double numericCellValue = cell.getNumericCellValue();
                    cellValue = format.format(numericCellValue);
                }
                break;
            case STRING:
            case BLANK:
                //处理字符串类型
                cellValue = cell.getStringCellValue();
                break;
            case BOOLEAN:
                //处理布尔类型
                boolean booleanCellValue = cell.getBooleanCellValue();
                cellValue = Boolean.toString(booleanCellValue);
                break;
            case FORMULA:
                //处理函数类型
                cellValue = cell.getCellFormula();
                break;
            case ERROR:
                byte errorCellValue = cell.getErrorCellValue();
                cellValue = Byte.toString(errorCellValue);
                break;
            default:
                break;
        }
        return cellValue;
    }
}
